package vip.wangwenhao.sso.config.security.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import vip.wangwenhao.autoconfigure.utils.Oauth2Utils;
import vip.wangwenhao.common.enums.ResultCode;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class TokenLoginAuthenticationFilter extends OncePerRequestFilter {

    private AuthenticationEntryPoint authenticationEntryPoint;

    private TokenStore tokenStore;

    private UserDetailsService userDetailsService;

    public TokenLoginAuthenticationFilter(AuthenticationEntryPoint authenticationEntryPoint, TokenStore tokenStore, UserDetailsService userDetailsService) {
        this.authenticationEntryPoint = authenticationEntryPoint;
        this.tokenStore = tokenStore;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final boolean debug = logger.isDebugEnabled();

        try {

            String token = Oauth2Utils.getToken(request);

            if (StringUtils.isBlank(token)) {
                chain.doFilter(request, response);
                return;
            }

            OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);

            if (null == oAuth2Authentication) {
                throw new AccountExpiredException(ResultCode.INVALID_TOKEN.getMessage());
            }

            Object principal = oAuth2Authentication.getPrincipal();
            String username = null;
            if (principal instanceof User) {
                username = ((User) principal).getUsername();
            }
            if (principal instanceof String) {
                username = String.valueOf(principal);
            }
            if (StringUtils.isNotBlank(username)) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //设置为已登录
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }


        } catch (AuthenticationException failed) {
            if (debug) {
                logger.debug(request.getRequestURI() + " Authentication request for failed: " + failed);
            }
            authenticationEntryPoint.commence(request, response, failed);
            return;
        }

        chain.doFilter(request, response);
    }
}